/*
@Time : 2020/7/30 10:49
@Author : lym
@File : UserController
@Software: GoLand
*/
package controller

import (
	"gin-YiStudio-V1/common"
	"gin-YiStudio-V1/common/consts"
	"gin-YiStudio-V1/common/response"
	"gin-YiStudio-V1/dao/dto"
	"gin-YiStudio-V1/dao/model"
	"gin-YiStudio-V1/service"
	"gin-YiStudio-V1/util"
	"github.com/astaxie/beego/logs"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

var (
	userService = service.UserServiceImpl{}
)

//注册
// @Summary 注册
// @Description 注册
// @Accept multipart/form-data
// @Produce json
// @Param name formData string false "name"
// @Param telephone formData string true "telephone"
// @Param password formData string true "password"
// @Success 200 {object} response.JsonResponse "{"code":200,"data":null,"msg":"注册成功"}"
// @Failure 100 {object} response.JsonResponse "{"code":200,"data":null,"msg":"手机号必须为11位"}"
// @Router /v1/api/auth/register [post]
func Register(ctx *gin.Context) {

	//获取参数
	name := ctx.PostForm("name")
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")
	logs.Info("Register:注册接口入参,name={%v},telephone={%v},password={%v}", name, telephone, password)

	//数据验证
	if len(telephone) != 11 {
		response.Ok(ctx, consts.ValiDatorError, nil, "手机号必须为11位")
		return
	}
	if len(password) < 6 {
		response.Bad(ctx, consts.ValiDatorError, nil, "密码不能小于6位")
		return
	}
	if len(name) == 0 {
		name = util.RandString(10)
		return
	}

	//判断手机号是否存在

	if userService.IsTelephoneExist(common.DB, telephone) {
		response.Bad(ctx, consts.UserExists, telephone, "用户已存在")
		return
	}

	//不存在则加密密码后新增

	hashPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		response.Bad(ctx, consts.EncryptionError, nil, "加密错误")
		return
	}

	newUser := model.User{
		UserName:  name,
		Telephone: telephone,
		PassWord:  string(hashPassword),
	}
	common.DB.Create(&newUser)

	response.Ok(ctx, 200, nil, "注册成功")
}

//登陆
// @Summary 登陆
// @Description 登陆
// @Accept multipart/form-data
// @Produce json
// @Param telephone formData string true "telephone"
// @Param password formData string true "password"
// @Success 200 {object} response.JsonResponse "{"code":200,"data":null,"msg":"登录成功"}"
// @Failure 100 {object} response.JsonResponse "{"code":200,"data":null,"msg":"手机号必须为11位"}"
// @Router /v1/api/auth/login [post]
func Login(ctx *gin.Context) {

	//获取参数
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")
	//数据验证
	if len(telephone) != 11 {
		response.Bad(ctx, consts.ValiDatorError, nil, "手机号必须为11位")
		return
	}
	if len(password) < 6 {
		response.Bad(ctx, consts.ValiDatorError, nil, "密码不能小于6位")
		return
	}

	if !userService.IsTelephoneExist(common.DB, telephone) {
		response.Bad(ctx, consts.UserNotExists, nil, "用户不存在")
		return
	}

	//校验密码
	err := bcrypt.CompareHashAndPassword([]byte(userService.User.PassWord), []byte(password))
	if err != nil {
		response.Bad(ctx, consts.PassWordError, nil, "密码错误")
		return
	}

	//返回结果
	//token 由三部分组成 第一部分是header头，存储的是token的加密协议，中间一部分是jwt.StandardClaims 信息，第三部分是前面两部分加key来hash的一个值
	token, err := common.ReleaseToken(userService.User)
	if err != nil {
		response.Bad(ctx, consts.SysErrorCode, nil, consts.SysErrorDesc)
	}
	response.Ok(ctx, 200, gin.H{
		"token": token,
	}, "登录成功")
}

/**
用户信息 GET 接口
*/

// @Summary 获取用户信息
// @Description 获取用户信息
// @Success 200 {object} response.JsonResponse {"code":200,"data":null,"msg":""}
// @Router /v1/api/auth/info [get]
func Info(ctx *gin.Context) {
	user, exists := ctx.Get("user")
	if exists {
		dto.ToUserDto(user.(*model.User))
		response.Ok(ctx, 200, user, "登录成功")
	}
	response.Bad(ctx, consts.UserNotExists, nil, "用户不存在")

}
